import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Node } from "@antv/x6";
import { Dnd } from "@antv/x6-plugin-dnd";
import { MessageService } from 'primeng/api';
import { Sidebar } from 'primeng/sidebar';
import { ControlLibComponent } from './control-lib/control-lib.component';
import { PiplineSettingComponent } from './pipline-setting/pipline-setting.component';
import { ScenarioSettingComponent } from './scenario-setting/scenario-setting.component';
import { SiteSettingComponent } from './site-setting/site-setting.component';
import { SrmSettingComponent } from './srm-setting/srm-setting.component';
import { CellType } from '../../enums';
import { ScenarioConfig, PiplineConifg, SiteNodeConfig, SrmConfig, CellConfig } from '../../models';
import { DesignGraphUtilService } from '../../services/design-graph-util.service';
import { ScenarioMetaService } from '../../services/scenario-meta.service';
import { ScenarioService } from '../../services/scenario.service';

@Component({
  selector: 'app-scenario-design',
  templateUrl: './scenario-design.component.html',
  styleUrl: './scenario-design.component.scss',
  providers: [
    DesignGraphUtilService
  ]
})
export class ScenarioDesignComponent implements OnInit, AfterViewInit, OnDestroy {
  scenario!: ScenarioConfig;
  createNew: boolean = true;

  // sidebarLeftVisible: boolean = false;
  scenarioChanged: boolean = false;


  @ViewChild("graphContainer", { static: true })
  graphContainer!: ElementRef;
  dnd?: Dnd;
  currentNode?: Node<Node.Properties>;

  @ViewChild("sidebarProps", { static: true })
  sidebarProps!: Sidebar;

  @ViewChild("scenarioSetting", { static: true })
  scenarioSetting!: ScenarioSettingComponent;

  @ViewChild("piplineSetting", { static: true })
  piplineSetting!: PiplineSettingComponent;
  @ViewChild("siteSetting", { static: true })
  siteSetting!: SiteSettingComponent;
  @ViewChild("srmSetting", { static: true })
  srmSetting!: SrmSettingComponent;
  @ViewChild("ctrlLib", { static: true })
  ctrlLib!: ControlLibComponent;

  get leftSidebarIcon() {
    return this.ctrlLib.isVisible ? 'pi pi-chevron-left' : 'pi pi-chevron-right';
  }

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private service: ScenarioService,
    private messageService: MessageService,
    private metaService: ScenarioMetaService,
    private util: DesignGraphUtilService
  ) { }

  ngOnInit(): void {
    this.util.cellselected.subscribe((cfg) => {
      this.scenario = this.util.getScenario();
      switch (cfg && cfg.Type) {
        case CellType.Pipline:
          const pipline = cfg as PiplineConifg;
          this.piplineSetting.onEdit(pipline);
          break;
        case CellType.Site:
          const site = cfg as SiteNodeConfig;
          this.siteSetting.onEdit(site);
          break;
        case CellType.Srm:
          const srm = cfg as SrmConfig;
          this.srmSetting.onEdit(srm);
          break;
      }
    });
  }

  ngAfterViewInit(): void {
    this.route.params.subscribe(params => {
      const { id } = params;
      this.util.Init(this.graphContainer.nativeElement);
      this.dnd = this.util.initDnd(this.ctrlLib.dndContainer.nativeElement);
      if (id == 'new') {
        this.scenario = {
          Name: "New Scenario",
          Lines: [],
          Srms: [],
        };
        this.createNew = true;
      } else {
        this.service.get(id).subscribe(item => {
          this.scenario = item;
          this.createNew = false;
          this.util.loadScenario(item);
          this.scenarioChanged = false;
        });
      }
    });
  }

  ngOnDestroy(): void {
    this.util.destroy();
  }

  startDrag(e: MouseEvent) {
    const target = e.currentTarget as HTMLElement;
    const type = target.getAttribute("data-type")!;
    const data = this.metaService.getMetaFromType(type);
    const node = this.util.createNode(data);
    this.dnd!.start(node, e);
  }

  onSaveToCloud() {
    const cfg = this.util.getScenario();
    cfg.Name = this.scenario.Name;
    if (this.scenario.Id) {
      cfg.Id = this.scenario.Id;
      this.service.updaet(cfg).subscribe(item => {
        this.messageService.add({ severity: 'success', summary: '更新成功', });
        this.router.navigate(['/scenarios', 'design', item.Id]);
      }, err => {
        console.log(err);
        this.messageService.add({ severity: 'warn', summary: '更新失败', detail: err.error.title });
      });
    } else {
      this.service.create(cfg).subscribe(item => {
        this.messageService.add({ severity: 'success', summary: '新建成功', });
        this.router.navigate(['/scenarios', 'design', item.Id]);
      });
    }
  }
  onShowJsonClick() {
    console.log(this.util.getScenario());

  }

  onShowLeftSidebar() {
    this.ctrlLib.toggle();
  }

  onSaveClick() {
    console.log("onSaveClick");
    const id = this.createNew ? undefined : this.scenario.Id;
    const config: ScenarioConfig = this.util!.getScenario();
    if (!this.createNew) {
      config.Id = id;
    }
    const key: string = "Scenario-" + (this.createNew ? "New" : this.scenario.Id);
    localStorage.setItem(key, JSON.stringify(config));
    this.messageService.add({ severity: 'success', summary: '本地保存成功', });
  }
  onLoadClick() {
    const key: string = "Scenario-" + (this.createNew ? "New" : this.scenario.Id);

    const json = localStorage.getItem(key);
    if (json) {
      const cfg: ScenarioConfig = JSON.parse(json);
      this.util?.loadScenario(cfg);
    }
  }

  onEditScenario() {
    this.scenarioSetting?.onEdit(this.scenario);
  }
  onEditScenarioComplate() {
    this.util.loadScenario(this.scenario);
  }
  onEditComplate(item: CellConfig) {
    console.log(item);
    this.util.updateScenarioNode(item);
  }
  onTestClick() {
    if (this.scenario.Id) {
      this.router.navigate(['/scenarios', 'monitor', this.scenario.Id]);
    }
  }
}
